import {t} from 'elysia'
import {ElysiaApp} from '..'
import {count, desc, eq, and, like} from 'drizzle-orm'
import {sysLoginLog, sysUser} from '../schema/schema'
import {toSql} from '../utils/dw'

export default (app: ElysiaApp) =>
  app
    // 获取用户分页列表
    .get(
      '/page/list',
      async ({db, query}) => {
        const {page, pageSize = 10, status, ip} = query
        const {id, ip: _ip, address, browser, os, status: _status, reason, createTime} = sysLoginLog
        const _res = await db.transaction(async tx => [
          await tx
            .select({id, user: {username: sysUser.username}, ip: _ip, address, browser, os, status: _status, reason, createTime})
            .from(sysLoginLog)
            .leftJoin(sysUser, eq(sysUser.id, sysLoginLog.userId))
            .where(
              and(
                toSql(status, e => eq(_status, e)),
                toSql(ip, e => like(_ip, `%${e}%`)),
              ),
            )
            .orderBy(desc(createTime), desc(id))
            .limit(pageSize)
            .offset((page - 1) * pageSize),
          await tx
            .select({total: count()})
            .from(sysLoginLog)
            .where(
              and(
                toSql(status, e => eq(_status, e)),
                toSql(ip, e => like(_ip, `%${e}%`)),
              ),
            ),
        ])
        return {list: _res[0], ..._res[1][0]}
      },
      {
        query: t.Object({
          page: t.Numeric(),
          pageSize: t.Optional(t.Numeric()),
          status: t.Optional(t.Numeric({minimum: 0, maximum: 1})),
          ip: t.Optional(t.String()),
        }),
      },
    )
